import hashlib
import json
import os
import re
from datetime import datetime
from random import randint

import requests
from django.conf import settings
from django.core.paginator import Paginator
from django.db import connection
from django.http import HttpResponse
from django.shortcuts import render, redirect

# 首页
from django.urls import reverse

from App.Code import Getcode
from App.models import User, Tags, Post, Draft, Comment
from App.sms import SMS

# 加密
def makepwd(pwd):
    new_pwd = str(pwd).encode('utf8')
    res = hashlib.md5(new_pwd).hexdigest()
    return res

# 基础页面
def base(request):
    return render(request,'base/base.html')

# 注册
def register(request):
    if request.method == 'GET':
        return render(request,'register.html')
    if request.method == 'POST':
        username = request.POST.get('uname')
        userpassword = request.POST.get('upassword')
        print(userpassword)
        userphone = request.POST.get('uphone')
#         头像获取
        userhoto = request.FILES.get('uphoto')
# #         拼接路径
        photopath = os.path.join(settings.MDEIA_ROOT,username+'.png')
        print(userpassword)
        with open(photopath,'wb') as fp:
            for i in userhoto.chunks():
                fp.write(i)
        # 保存去数据库
        user = User()
        user.username = username
        user.userpasswd = makepwd(userpassword)
        # print (makepwd(userpassword))
        user.userphone = userphone
        user.userimg = photopath
        user.username = username
        user.save()
        #     把session保存到数据库
        request.session['uname'] = username
        request.session['upassword'] = makepwd(userpassword)
        return redirect(reverse('App:index'))

# 验证用户名
def check_username(request):
#     去数据库查找用户名是否存在
    username = request.GET.get('uname')
    user = User.objects.filter(username=username)
    if user.exists():
        res = json.dumps({'code': 1, 'msg': '用户已存在'})
        return HttpResponse(res)

    res = json.dumps({'code': 0, 'msg': '用户名可用'})
    return HttpResponse(res)

# 验证密码
def check_password(request):
    pwd = request.GET.get('userpwd')
    if pwd:
        newpwd = str(pwd)
        if len(newpwd)>5:
            ret = re.search(r'(^[a-zA-Z]\d+\w*)',newpwd,re.I)
            # print (ret)
            if ret:
                # print('2')
                res = json.dumps({'code': 1, 'msg': '正确的密码格式'})
                # print(res)
                return HttpResponse(res)
            else:
                # print('3')
                res = json.dumps({'code':2, 'msg': '请输入字母与数字的结合'})
                # print(res)
                return HttpResponse(res)
        else:
            res = json.dumps({'code': 0, 'msg': '密码长度不够，请重新输入'})
            return HttpResponse(res)
    return HttpResponse(json.dumps({'code': 3, 'msg': '请输入密码'}))


# 发送手机验证码
def sendyzm(request):
    phone = request.GET.get('phone')
    sms = SMS('成少雷', 'SMS_102315005')
    num = randint(100000, 999999)
    request.session['yzm'] = num
    res = sms.send_sms(phone, num)
    return HttpResponse(res)

# 得到图片验证码
def getcode(request):
    obj = Getcode()
    # 把得到的二进制返回
    getcode = obj.output()
    ret = obj.code
    # 这个是明文显示的验证码
    # print(getcode)
    # 给这个验证码带上code
    request.session['code'] = ret
    # 传输的是二进制流，所以以图片并且是png的格式返回
    return HttpResponse(getcode, 'image/png')


# 登录
def login(request):
    if request.method == 'GET':
        return render(request,'login.html')
    if request.method == 'POST':
        yzm = request.session.get('yzm')
        yzm = str(yzm)

        code = request.POST.get('sms')
        print(yzm, code)
        # 手机验证码
        if yzm == code:
            # 去数据库判断用户名密码是否正确
            username = request.POST.get('uname')
            password = request.POST.get('upassword')
            new_password = makepwd(password)
            user = User.objects.filter(username=username, userpasswd=new_password)
            # 先判断验证码
            codedata = request.POST.get('yzmcode')
            # print(codedata)
            # 得到session的验证码
            scodedata = request.session.get('code')
            print(scodedata)
            if codedata == scodedata:
                if user.exists():
                    # 同时再设置session过去首页
                    request.session['uname'] = username
                    request.session['upassword'] = new_password
                    return redirect(reverse('App:index'))
                else:
                    data = {
                        'code': -1,
                        'msg': '用户名或密码错误，请重写输入',
                        'wait': 3,
                        'url': "/App/login/"
                    }
                    return render(request, 'notice.html', data)
            else:
                data = {
                    'code': -2,
                    'msg': '验证码错误，请重写输入',
                    'wait': 3,
                    'url': "/App/login/"
                }
                return render(request, 'notice.html', data)
        else:
            data = {
                'code': -3,
                'msg': '手机验证码错误，请重写输入',
                'wait': 3,
                'url': "/App/login/"
            }
            return render(request, 'notice.html', data)


# 退出登录
def logingout(request):
    # 清除缓存
    request.session.flush()
    return redirect(reverse('App:index'))


# 首页
def index(request,num='1'):
    # 获取session
    usession = request.session.get('uname')

    # imgurl = '/static/upload/%s.png ' %(usession)
    # print(imgurly)
    # 得到排名前几的文章
    posts = Post.objects.filter(is_delete=False).order_by('-views')[:10]

    paginator = Paginator(posts, 3)
    # 创建分页对象
    current = int(num)

    page = paginator.page(current)

    # 自定义页码范围
    if paginator.num_pages > 10:
        # 　如果当前页码减去5小于0
        if current - 5 <= 0:
            customRange = range(1, 11)
        elif current + 5 > paginator.num_pages:
            customRange = range(paginator.num_pages - 9, paginator.num_pages + 1)
        else:
            customRange = range(current - 5, current + 5)
    else:
        customRange = paginator.page_range
    # 得到分类
    tags = Tags.objects.all()
    data = {
        'post':posts,
        'usession':usession,
        'tags':tags,
        'data': page.object_list,
        'pagerange': customRange,  # 页码范围
        'page': page
    }
    return render(request,'index.html',data)

# 关于我
def aboutme(request):
    session = request.session.get('uname')
    if session:
        # 得到文章总数，评论，和访问量
        name = request.session.get('uname')
        # 取出本用户关联的所有博客
        user = User.objects.filter(username=name)[0]
        post = user.post_set.filter(is_delete=False).count()
        # 得到草稿箱的数量
        draft = user.draft_set.count()
        comment = user.comment_set.count()
        data = {
            'post':post,
            'usession':name,
            'draft':draft,
            'comment':comment
        }
        return render(request,'aboutme.html',data)
    else:
        return render(request, 'login.html')

# 博客
def article(request):
    usersession = request.session.get('uname')
    # 还是得根据用户id取数据
    user = User.objects.filter(username=usersession)[0]
    post = user.post_set.filter(is_delete=False).order_by('-pub_date')

    # 对数据进行排序
    data = {
        'usersession':usersession,
        'post':post,
    }
    return render(request,'article.html',data)

# 添加文章
def addarticle(request):
    if request.method == 'GET':
        # 用户id传过来
        usession = request.session.get('uname')
        tags = Tags.objects.all().values()
        tagslist = []
        for t in tags:
            tagslist.append(t.get('name'))
        data = {
            'usession':usession,
            'tagslist':tagslist,
        }
        return render(request,'add-article.html',data)
    if request.method == 'POST':
        username = request.session.get('uname')
        # print(username)
        user = User.objects.get(username=username)
        # print (user)
        title = request.POST.get('title')
        content = request.POST.get('mycontent').split('>')[1].split('<')[0]
        # print(title)
        print(content)
        tags = request.POST.getlist('category')
        # print ('-----')
        print(tags)
        taglt = []
        for i in tags:
            itag = Tags.objects.get(name=i)
            taglt.append(itag)
        pub_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # # 保存去数据库
        # # 多对多
        post = Post()
        post.user = user
        post.title = title
        post.content = content
        post.pub_date = pub_date
        post.save()
        # # 在多对多中，一定要先保存数据，再add添加
        for i in taglt:
            post.tags.add(i)
        return redirect(reverse('App:aboutme'))
        # return HttpResponse('test')

# 分类展示
def moodlist(request,tid='0'):
    usession = request.session.get('uname')
    # 判断是否有置顶
    if tid == '0':
        post = Post.objects.all().order_by('-is_top')
        title ='全部博客'
        data = {
            'post': post,
            'usession': usession,
            'title': title
        }
        return render(request, 'moodlist.html', data)
    else:
        tag = Tags.objects.get(pk = tid)
        post = tag.post_set.all().order_by('-is_top')
        title = tag.name
        data = {
            'post': post,
            'usession': usession,
            'title': title
        }
        return render(request, 'moodlist.html', data)

#阅读全文
def makeviews(request,pid):
    username = request.session.get('uname')
    post = Post.objects.get(pk=pid)
    request.session['title'] = post.title
    comment = post.comment_set.all().order_by('-pub_date')
    # print(comment.count())
    data = {
        'post':post,
        'comment': comment,
        'usession':username
    }
    return render(request, 'new.html', data)


# 点击量
def deal(request,num):
    title = request.session.get('title')
    post = Post.objects.get(title = title)
    print (post)
    views = post.views
    views += int(num)
    post.views = views
    post.save()
    return None

# 填写评论
def comment(request,pid):
    # 判断是否登录
    session = request.session.get('uname')
    if session:
        mycomment = request.POST.get('mycomment')
        user = User.objects.get(username=session)
        post = Post.objects.get(pk=pid)
        print(mycomment, user, post)
        pub_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        comment = Comment()
        comment.user = user
        comment.post = post
        comment.content = mycomment
        comment.pub_date = pub_date
        comment.save()
        # 反向解析
        return redirect(reverse('App:makeviews',args=(pid,)))
    else:
        return render(request,'login.html')

# 删除
def delete(request,pid):
    print(pid)
    # 去数据库查找
    post = Post.objects.get(pk=int(pid))
    post.is_delete = True
    post.save()
    return render(request,'aboutme.html')

# 修改
def update(request,pid):
    if request.method == 'GET':
        # print(uid)
        # 用户id传过来
        usession = request.session.get('uname')
        # print(usession)
        tags = Tags.objects.all().values()
        # print(tags)
        tagslist = []
        for t in tags:
            tagslist.append(t.get('name'))
        #     把用户数据库的也传过去
        print(tagslist)
        user = User.objects.get(username=usession)
        # print(user)
        post = Post.objects.get(pk=int(pid))
        # print (post.id)
        # # 查出来所选中的tags标签
        # # 得到的是对象列表
        p_tags = post.tags.all()
        plt = []
        for i in p_tags:
            plt.append(i.name)
        print(plt)
        data = {
            'usession': usession,
            'tagslist': tagslist,
            'post':post,
            'p_tags':plt,
            'pid':pid,
        }
        return render(request, 'update-article.html', data)

    if request.method == 'POST':
        username = request.session.get('uname')
        user = User.objects.get(username=username)

        title = request.POST.get('title')
        content = request.POST.get('content').split('>')[1].split('<')[0]

        taglist = request.POST.getlist('category')
        taglt = []
        for i in taglist:
            itag = Tags.objects.get(name=i)
            taglt.append(itag)
        pub_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # # # # 保存去数据库
        # # # # 多对多
        post = Post.objects.get(pk=pid)
        # 根据post删除相关的分类关系
        num = post.id
        # # # 多对多添加之前，先删除他们的外键
        with connection.cursor() as cursor:
            # 防止sql注入
            cursor.execute("delete from App_post_tags where post_id=%s", [num])
        # print(post.id)
        post.user = user
        post.title = title
        post.content = content
        post.pub_date = pub_date
        post.save()
        # # # # # 在多对多中，一定要先保存数据，再add添加
        for i in taglt:
            post.tags.add(i)
        return redirect(reverse('App:article'))

#草稿箱
def draft(request):
    if request.method == 'GET':
        # 用户id传过来
        usession = request.session.get('uname')
        user = User.objects.get(username=usession)
        # 把数据传过来
        # 拿草稿箱
        draft = user.draft_set.all().order_by('-pub_date')
        data = {
            'usession':usession,
            'draft':draft
        }
        return render(request, 'draft.html',data)
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content').split('>')[1].split('<')[0]
        # print(request.POST)
        myarr = request.POST.getlist('myarr[]')
        print (title,content)
        print (myarr)
        username = request.session.get('uname')
        user = User.objects.get(username=username)
        title = request.POST.get('title')
        # print(content)
        tags = request.POST.getlist('category')
        # print(tags)
        taglt = []
        for i in tags:
            itag = Tags.objects.get(name=i)
            taglt.append(itag)
        pub_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        # # # 保存去数据库
        # # # 多对多
        draft = Draft()
        draft.user = user
        draft.title = title
        draft.content = content
        draft.pub_date = pub_date
        draft.save()
        # # 在多对多中，一定要先保存数据，再add添加
        for i in taglt:
            draft.tags.add(i)
        return redirect(reverse('App:draft'))

# 展示评论
def mycomment(request):
    usession = request.session.get('uname')
    user = User.objects.get(username=usession)
    comment = user.comment_set.all()
    data = {
        'usession': usession,
        'comment': comment,
    }
    # 把数据传过来
    return render(request, 'comment.html', data)

# 置顶
def istop(request,pid):
    # 先把原来的取消掉
    oldpost = Post.objects.filter(is_top=True)
    print(oldpost)
    for i in oldpost:
        i.is_top = False
        i.save()
    # #     再添加
    post = Post.objects.get(pk = pid)
    post.is_top = True
    post.save()
    data = {
        'code': 1,
        'msg': '已经完成置顶',
        'wait': 3,
        'url': "/App/moodlist/0"
    }
    return render(request,'notice.html',data)


def test(request):
    url = 'http://datamining.comratings.com/exam'
    response = requests.get(url=url)
    cookies = response.cookies.values()[0]
    return render(request,'test.html',{'cookies':cookies})

def test3(request):
    url = 'http://datamining.comratings.com/exam3'
    a1 = request.GET.get('a1')
    # print(a1)
    a2 = request.GET.get('a2')
    # print(a2)
    cookies = request.GET.get('cookies')
    # print(cookies)
    headers = {
        'Cookie':'session='+cookies+'; c1='+a1+'; c2='+a2
    }
    response = requests.get(url=url,headers = headers)
    print(response.text)
    with open('作业.html','w') as fp:
        fp.write(response.text)
    return HttpResponse('完成')


def test2(request):
    return render(request,'作业.html')